/// <reference path="../brandIE.controls.js" />
/// <reference path="../brandIE.controls.eventObserver.js" />
(function ($) {
    var ns_store = nsbase.controls.store = Store;

    //数据存储类
    function Store(config) {
        var _self = this;
        var _eventObserver = new nsbase.controls.eventObserver(_self);

        var _default = {
            remote: true,
            url: "",
            methodType: "POST",//Get
            data: {},
            pageIndex: 0,// 0:no pagging   start page index:1
            pageSize: 0,// 0:no pagging    start page size:1
            pageRemote: false,
            sortField: "",
            sortDirect: "ASC",
            resultSetName: "results",//默认的结果对象集字段名
            totalCountName: "totalCount"//默认的结果集总数字段名（分页时用到）
        };

        var _config, _results, _totalCount, _actionParams;

        function _init() {
            _config = $.extend(true, {}, _default, config);
            _actionParams = _config.data;
            if (_config.pageRemote) {
                _actionParams.pageSize = _config.pageSize;
            }
        }
        _init();

        //#region Public methods

        _self.on = _eventObserver.on;
        _self.un = _eventObserver.un;
        _self.unAll = _eventObserver.unAll;

        _self.load = function (params) {
            loadData(params);
        }

        _self.reLoad = function (params) {
            loadData(params);
        }

        _self.getResults = function () {
            return _results;
        }

        _self.getResultsCount = function () {
            if (_config.pageRemote && _totalCount) {
                return _totalCount;
            }
            return _results.length;
        }

        _self.setResults = function (data) {
            if (!data)
                data = [];
            onDataBind(data);
        }

        //排序
        _self.sort = sortData;

        //#endregion

        //#region Register Methods

        function onBeforeLoad() {
            _eventObserver.fireEvent(Store.setting.eventEnums.beforeLoad);
        }

        function onDataReceived(data) {
            _eventObserver.fireEvent(Store.setting.eventEnums.dataReceived, [data]);
        }

        function onDataBind(data) {
            _eventObserver.fireEvent(Store.setting.eventEnums.dataBind, data);
        }

        function onDataError(error) {
            _eventObserver.fireEvent(Store.setting.eventEnums.dataError, error);
        }

        //#endregion


        //获取数据，通过Ajax方式获取数据
        function loadData(params) {
           
            if (!_config.remote) {
                return;
            }
            
            _actionParams = $.extend(true, _actionParams, (params || {}));
            if (!_config.url) {
                throw new Error("The action url is empty!");
            }
            onBeforeLoad();
            $.ajax({
                cache: false,
                url: _config.url,
                contentType:"application/json",
                dataType: "json",
                type: _config.methodType,
                data: JSON.stringify(_actionParams),
                success: function (data, textStatus, XMLHttpRequest) {
                    onDataReceived(data);
                    if(!data && data.data){
                        data = {data:{}};
                        data.data[_config.resultSetName] = {};
                        data.data[_config.totalCountName] = 0;
                    }
                    _results = data.data[_config.resultSetName] || data.data;

                    if (_config.pageRemote) {
                        _totalCount = data.data[_config.totalCountName];
                        onDataBind();
                    } else {
                        var pageResults = getPageResults(_config.pageIndex);
                        onDataBind([pageResults]);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    _results = [];
                    onDataError(errorThrown);
                }
            });
        }


        function getPageResults(pageIndex) {
            if(_results&&_results.length>0){
                if (pageIndex) {
                    _config.pageIndex = pageIndex;
                }
                var startIndex = (_config.pageIndex - 1) * _config.pageSize;
                var endIndex = startIndex + _config.pageSize;
                return _results.slice(startIndex, endIndex);
            } else {
                return null;
            }
        }

        function sortData(sortField, sortDirection) {
            var param = {
                sortField: sortField || "",
                sortDirect: sortDirection || "ASC"
            };
            if (!_config.pageRemote) {
                resortData(param.sortField, param.sortDirect);
                return;
            }
            loadData(param);
        }

        //对加载的数据排序
        function resortData(field, direction) {
            var dir = direction;
            var f = field;
            function sortFunc(r1, r2) {
                var v1 = r1[f], v2 = r2[f];
                if (v1 == null) v1 = "";
                if (v2 == null) v2 = "";
                var result = v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
                if (String(dir).toUpperCase() == 'ASC')
                    return result;
                else
                    return result * -1;
            }
            var pageResults = getPageResults();
            pageResults.sort(sortFunc);
        }

    /*
        //#region  
    
        var me = this;
        //$.extend(true, me, adSage.Observable);    //继承观察者对象
        var defaults = {
            root: 'rows',
            totalProperty: 'results',
            dataType: 'json',
            autoLoad: false,
            sortInfo: { field: '', direction: 'ASC' },
            pageParam: { PageIndex: 0, PageSize: 20, OrderField: "", OrderDirection: "ASC" },
            proxy: { method: 'POST' },
            remoteSort: false
        }, //默认配置
        resultRows = [], rowCount = 0, totalCount = 0,
        eventCollection = {
            load: [],
            exception: [],
            beforeload: [],
            sortchanged: [],
            datachanged: [],
            beforesave: [],
            saved: [],
            datareceived: [],
            dataappended: []
        }, //事件集合
        olderQueryParams = config.params || {}; //上次查询的参数
        //adSage.apply(me, config, defaults); //加载参数
        //me.addEvents(eventCollection);
        $.extend(true, me, defaults, config);
        var storeSetting = Store.setting;
    
    
        //#endregion
    
    
        //#region  
    
        //加载数据
        me.load = function (params) {
            loadData(params);
        };
        //重新加载
        me.reload = function (params) {
            loadData(params);
        };
        //获取加载的数据量
        me.getCount = function () {
            return rowCount;
        };
        //获取表格源数据的总数
        me.getTotalCount = function () {
            return totalCount;
        };
        //设置表格数据
        me.changeData = function (records, dataItems, model) {
            changedData(records, dataItems, model);
        };
    
        me.setResult = function (data) {
            if (!data)
                data = [];
            resultRows = data;
            rowCount = totalCount = resultRows.length;
            onLoadData();
        }
        //获取加载的数据对象
        me.getResult = function () {
            return resultRows;
        };
        //获取指定编号的记录
        me.getAt = function (index) {
            return resultRows[index];
        };
        //查找记录
        me.find = function (fieldName, value, startIndex) {
    
        };
    
        me.save = function (records, dataItems) {
            saveData(records, dataItems);
        };
        // 创建数据
        me.create = function (record) {
            createData(record);
        }
    
        me.remove = function (records) {
            removeData(records);
        }
        //排序
        me.sort = function (field, direction) {
            //todo: [OldReportTracking]
            if (field) {
                me.sortInfo.field = field;
            }
            if (direction) {
                me.sortInfo.direction = direction;
            } else {
                me.sortInfo.direction = 'ASC';
            }
    
            me.pageParam.OrderField = me.sortInfo.field;
            me.pageParam.OrderDirection = me.sortInfo.direction;
            if (!me.remoteSort) {
                resortData();
                onSortChanged();
            } else {
                loadData();
            }
        };
    
        me.appendFilterData = function (data, compareFields) {
            appendFilterData(data, compareFields);
        };
        //me.on = me.addListener;
        //me.un = me.removeListener;
    
        me.on = _eventObserver.on;
        me.un = _eventObserver.un;
        me.unAll = _eventObserver.unAll;
    
        //#endregion
    
        //获取数据，通过Ajax方式获取数据
        function loadData(params) {
            // zjk todo
            //            if(!me.autoLoad){
            //                return;
            //            }
            onBeforeLoad();
            var loadparams = params || {};
            $.extend(olderQueryParams, loadparams);
            //adSage.apply(olderQueryParams, loadparams);
            if (!me.proxy.url) {
                me.proxy.url = me.url;
            }
            $.extend(loadparams, olderQueryParams);
            //adSage.apply(loadparams, olderQueryParams);
            loadparams.pageParam = me.pageParam;
            //todo: [OldReportTracking]
            loadparams.field = me.sortInfo.field ? me.sortInfo.field : "";
            if (!loadparams.direction) {
                loadparams.direction = me.sortInfo.direction ? me.sortInfo.direction : "ASC";
            }
            $.ajax({
                cache: false,
                url: me.proxy.url,
                dataType: me.dataType,
                contentType: "application/json",
                type: me.proxy.method,
                //data: loadparams ? jQuery.param(adSage.toMvcString(loadparams)) : '',
                data: loadparams,
                success: function (data, textStatus, XMLHttpRequest) {
                    onDataReceived(data);
                    resultRows = data;
                    onLoadData(me);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    resultRows = [];
                    rowCount = 0;
                    totalCount = 0;
                    onError();
                }
            });
        }
    
        function changedData(records, dataItems, model) {
            onDataChanged(records, dataItems);
        }
    
        // 更新时保存数据
        function saveData(records, fieldItems) {
            //var params = {};
            //// zjk savedata
            //var searEngine = adSage.utility.semObject.getSearchEngineByDetailType(records[0].ObjectDetailTypeId);
            //if (searEngine == adSage.enums.SearchEngineType.Facebook) {
            //    var recordIds = [], dataItems = [];
            //    onBeforeSave(records, fieldItems[0].key, fieldItems[0].value, [], []);
            //    $.each(fieldItems, function (index, item) {
            //        dataItems.push({ key: item.key, value: item.value, dataIndex: item.dataIndex });
            //    });
    
            //    $.each(records, function (index, record) {
            //        recordIds.push(record.LocalId);
            //    });
            //    params = adSage.toMvcString({ recordIds: recordIds, dataItems: dataItems }, false);
            //}
            //else {
            //    var filteredRecords = [];
            //    var updatedRecords = [];
            //    //记录需要修改的records的引用
            //    if (onBeforeSave(records, fieldItems[0].key, fieldItems[0].value, filteredRecords, updatedRecords) !== false) {
            //        if (!me.update) {
            //            changedData(records, fieldItems);
            //            onSaved();
            //            return;
            //        }
            //        var sendRecords = filteredRecords.length ? filteredRecords : records;
            //        updatedRecords = updatedRecords.length ? updatedRecords : records;
    
            //        params = adSage.toMvcString({ records: sendRecords, field: fieldItems[0].key, value: fieldItems[0].value }, true);
            //    }
            //}
            //$.ajax({
            //    cache: false,
            //    url: me.update.url,
            //    dataType: 'json',
            //    type: 'POST',
            //    data: params,
            //    success: function (data, textStatus, XMLHttpRequest) {
            //        if (data && data.Success === true) {
            //            onSaved();
            //            var changedDatas = (updatedRecords ? updatedRecords : records);
            //            changedData(changedDatas, fieldItems, data.Model);
            //            if (searEngine == adSage.enums.SearchEngineType.Facebook) {
            //                alert(SR.SaveSuccess);
            //            }
            //        } else {
            //            if (data == null) {
            //                onError();
            //            } else if (data.ValidateErrorMap) {
            //                onError(data.ValidateErrorMap[fieldItems[0].key]);
            //            } else {
            //                onError(data.ErrorMessage);
            //            }
            //        }
            //    },
            //    error: function (XMLHttpRequest, textStatus, errorThrown) {
            //        onError(me.update.errorMsg);
            //    }
            //});
        }
    
        // 创建数据
        function createData(record) {
            //$.ajax({
            //    cache: false,
            //    url: me.add.url,
            //    dataType: 'json',
            //    type: 'POST',
            //    data: adSage.toMvcString({ creatObj: record }),
            //    success: function (data, textStatus, XMLHttpRequest) {
            //        if (data && data.Success === true) {
            //            var parentNodeId = record.ParentId + "_" + adSage.utility.semObject.getParentDetailTypeIdByDetailTypeId(record.ObjectDetailType);
            //            top.accountTreeListener.onCreateNode(parentNodeId);
            //            loadData();
            //        } else {
            //            if (data == null) {
            //                onError();
            //            } else if (data.ValidateErrorMap) {
            //                onError(AdSageUtility.Obj2str(data.ValidateErrorMap));
            //            } else {
            //                onError(me.add.errorMsg);
            //            }
            //        }
            //    },
            //    error: function (XMLHttpRequest, textStatus, errorThrown) {
            //        onError(me.add.errorMsg);
            //    }
            //});
        }
    
        // 移除数据 未用到
        function removeData(records) {
            //$.ajax({
            //    cache: false,
            //    url: me.remove.url,
            //    dataType: 'json',
            //    type: 'POST',
            //    data: adSage.toMvcString({ records: records }),
            //    success: function (data, textStatus, XMLHttpRequest) {
            //        if (data && data.Success === true) {
            //            onSaved();
            //            //                            changedData(updatedRecords, fieldItems, data.Model);
            //        } else {
            //            if (data == null) {
            //                onError();
            //            } else if (data.ValidateErrorMap) {
            //                onError(AdSageUtility.Obj2str(data.ValidateErrorMap));
            //            } else {
            //                onError(me.remove.errorMsg);
            //            }
            //        }
            //    },
            //    error: function (XMLHttpRequest, textStatus, errorThrown) {
            //        onError(me.remove.errorMsg);
            //    }
            //});
        }
    
        //对加载的数据排序
        function resortData(field, direction) {
            var dir = me.sortInfo.direction || 'ASC';
            var f = me.sortInfo.field;
            function sortFunc(r1, r2) {
                var v1 = r1[f], v2 = r2[f];
                if (v1 == null) v1 = "";
                if (v2 == null) v2 = "";
                var result = v1 > v2 ? 1 : (v1 < v2 ? -1 : 0);
                if (String(dir).toUpperCase() == 'ASC')
                    return result;
                else
                    return result * -1;
            }
            resultRows.sort(sortFunc);
    
        }
    
        //追加数据并去重
        function appendFilterData(data, compareFields) {
            if (!data || data.length == 0) {
                return;
            }
    
            var cFields = [], filterData = [];
            if (compareFields && compareFields.length > 0) {
                cFields = compareFields;
            }
            else {
                for (var key in data[0]) {
                    cFields.push(key);
                }
            }
    
            function compareDataItem(data1, data2, fields) {
                var ret = true;
                for (var i in fields) {
                    if (data1[fields[i]] != data2[fields[i]]) {
                        ret = false;
                        break;
                    }
                }
    
                return ret;
            }
    
            function checkDataExist(items, item, fields) {
                var ret = false;
                for (var i in items) {
                    if (compareDataItem(items[i], item, fields)) {
                        ret = true;
                        break;
                    }
                }
    
                return ret;
            }
    
            for (var i in data) {
                if (!checkDataExist(resultRows, data[i], cFields)) {
                    resultRows.push(data[i]);
                    filterData.push(data[i]);
                }
            }
    
            if (filterData.length > 0) {
                onDataAppended(filterData);
            }
        }
    
        //加载前
        function onBeforeLoad() {
            _eventObserver.fireEvent(storeSetting.eventEnums.beforeLoad);
        }
        //触发加载完成事件
        function onLoadData(params) {
            _eventObserver.fireEvent(storeSetting.eventEnums.load, params);
        }
        //加载过程中发生错误
        function onError(params) {
            _eventObserver.fireEvent(storeSetting.eventEnums.exception, params);
        }
    
        //排序发生改变（本地排序）
        function onSortChanged() {
            _eventObserver.fireEvent(storeSetting.eventEnums.sortChanged);
        }
    
        function onBeforeSave(records, field, value, filteredRecords, updatedRecords) {
            //return me.fireEvent('beforesave', me, records, field, value, filteredRecords, updatedRecords);
            var params = {};
            _eventObserver.fireEvent(storeSetting.eventEnums.beforeSave, params);
        }
    
        function onSaved() {
            _eventObserver.fireEvent(storeSetting.eventEnums.saved);
        }
    
        function onDataChanged(records, dataItems) {
            var params = {};
            _eventObserver.fireEvent(storeSetting.eventEnums.dataChanged, params);
        }
    
        function onDataReceived(data) {
            _eventObserver.fireEvent(storeSetting.eventEnums.dataReceived, data);
        }
    
        function onDataAppended(records) {
            _eventObserver.fireEvent(storeSetting.eventEnums.dataAppended, records);
        }
        */
    };

    Store.setting = new StoreSetting();
    function StoreSetting() {
        var _self = this;
        function _init() {
            _self.eventEnums = new StoreEventEnums();
        }
        _init();
    }
    function StoreEventEnums() {
        var _self = this;
        //_self.load = 'load';
        //_self.exception = 'exception';
        //_self.beforeLoad = 'beforeLoad';
        //_self.sortChanged = 'sortChanged';
        //_self.dataChanged = 'dataChanged';
        //_self.beforeSave = 'beforeSave';
        //_self.saved = 'saved';
        //_self.dataReceived = 'dataReceived';
        //_self.dataAppended = 'dataAppended';

        _self.beforeLoad = "beforeLoad";
        _self.dataReceived = "dataReceived";
        _self.dataBind = "dataBind";
        _self.dataError = "dataError";
    }

})(jQuery);